﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;

namespace DataService.Helper
{
    public class MySqlHelper
    {
        LogHelper logHelper = new LogHelper();
        private string connstr = ConfigurationManager.ConnectionStrings["MySql"].ConnectionString;// "";
        MySqlConnection connection;
        public MySqlHelper()
        {
            connection = new MySqlConnection(connstr);
        }
        public MySqlHelper(string connectionString)
        {
            connstr = connectionString;
            connection = new MySqlConnection(connstr);
        }
        /// <summary>
        /// 打开数据库连接
        /// </summary>
        /// <returns></returns>
        public bool Open()
        {
            try
            {
                if (connection == null) return false;
                if (connection.State != ConnectionState.Open)
                {
                    return true;
                }
                else
                {
                    connection.Open();
                }
            }
            catch (MySqlException ex)
            {
                logHelper.Error(ex.Message + "\r\n" + ex.StackTrace);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 关闭数据库连接
        /// </summary>
        /// <returns></returns>
        public bool Close()
        {
            try
            {
                if (connection == null) return false;
                if (connection.State != ConnectionState.Closed)
                {
                    return true;
                }
                else
                {
                    connection.Close();
                }
            }
            catch (MySqlException ex)
            {
                logHelper.Error(ex.Message + "\r\n" + ex.StackTrace);
                return false;
            }
            return true;
        }

        #region 执行查询语句，返回MySqlDataReader

        /// <summary>
        /// 执行查询语句，返回MySqlDataReader
        /// </summary>
        /// <param name="sqlString"></param>
        /// <returns></returns>
        public MySqlDataReader ExecuteReader(string sqlString)
        {
            MySqlConnection connection = new MySqlConnection(connstr);
            MySqlCommand cmd = new MySqlCommand(sqlString, connection);
            MySqlDataReader myReader = null;
            try
            {
                connection.Open();
                myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return myReader;
            }
            catch (Exception e)
            {
                connection.Close();
                throw new Exception(e.Message);
            }
            finally
            {
                if (myReader == null)
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }
        #endregion

        #region 执行带参数的查询语句，返回 MySqlDataReader

        /// <summary>
        /// 执行带参数的查询语句，返回MySqlDataReader
        /// </summary>
        /// <param name="sqlString"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public MySqlDataReader ExecuteReader(string sqlString, params MySqlParameter[] cmdParms)
        {
            MySqlConnection connection = new MySqlConnection(connstr);
            MySqlCommand cmd = new MySqlCommand();
            MySqlDataReader myReader = null;
            try
            {
                PrepareCommand(cmd, connection, null, sqlString, cmdParms);
                myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (Exception e)
            {
                connection.Close();
                throw new Exception(e.Message);
            }
            finally
            {
                if (myReader == null)
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }
        #endregion

        #region 执行sql语句,返回执行行数

        /// <summary>
        /// 执行sql语句,返回执行行数
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public int ExecuteSql(string sql)
        {
            if (!Open()) return 0;
            using (MySqlCommand cmd = new MySqlCommand(sql, connection))
            {
                try
                {
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (MySql.Data.MySqlClient.MySqlException e)
                {
                    logHelper.Error(e.Message);
                }
                finally
                {
                    cmd.Dispose();
                }
            }

            return -1;
        }
        #endregion

        #region 执行带参数的sql语句，并返回执行行数

        /// <summary>
        /// 执行带参数的sql语句，并返回执行行数
        /// </summary>
        /// <param name="sqlString"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public int ExecuteSql(string sqlString, params MySqlParameter[] cmdParms)
        {
            if (!Open()) return 0;
            using (MySqlCommand cmd = new MySqlCommand())
            {
                try
                {
                    PrepareCommand(cmd, connection, null, sqlString, cmdParms);
                    int rows = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    return rows;
                }
                catch (Exception E)
                {
                    throw new Exception(E.Message);
                }
                finally
                {
                    cmd.Dispose();
                }
            }
        }
        #endregion

        #region 执行查询语句，返回DataSet

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataSet GetDataSet(string sql)
        {
            DataSet ds = new DataSet();
            if (!Open()) return ds;
            try
            {
                MySqlDataAdapter DataAdapter = new MySqlDataAdapter(sql, connection);
                DataAdapter.Fill(ds);
            }
            catch (Exception ex)
            {
                logHelper.Error(ex.Message + "\r\n" + ex.StackTrace + "\r\n" + sql);
            }
            return ds;
        }
        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataTable GetDataTable(string sql)
        {
            DataTable dt = new DataTable();
            if (!Open()) return dt;
            try
            {
                MySqlDataAdapter DataAdapter = new MySqlDataAdapter(sql, connection);
                DataAdapter.Fill(dt);
            }
            catch (Exception ex)
            {
                logHelper.Error(ex.Message + "\r\n" + sql);
            }
            return dt;
        }
        #endregion

        #region 执行带参数的查询语句，返回DataSet

        /// <summary>
        /// 执行带参数的查询语句，返回DataSet
        /// </summary>
        /// <param name="sqlString"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public DataSet GetDataSet(string sqlString, params MySqlParameter[] cmdParms)
        {
            DataSet ds = new DataSet();
            if (!Open()) return ds;
            MySqlCommand cmd = new MySqlCommand();
            PrepareCommand(cmd, connection, null, sqlString, cmdParms);
            using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
            {
                try
                {
                    da.Fill(ds, "ds");
                    cmd.Parameters.Clear();
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message + "\r\n" + ex.StackTrace + "\r\n" + sqlString + "\r\n" + JsonConvert.SerializeObject(cmdParms));
                }
                finally
                {
                    cmd.Dispose();
                }
                return ds;
            }
        }
        #endregion

        #region 执行带参数的sql语句，并返回 object

        /// <summary>
        /// 执行带参数的sql语句，并返回object
        /// </summary>
        /// <param name="sqlString"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public object GetSingle(string sqlString, params MySqlParameter[] cmdParms)
        {
            if (!Open()) return 0;
            using (MySqlCommand cmd = new MySqlCommand())
            {
                try
                {
                    PrepareCommand(cmd, connection, null, sqlString, cmdParms);
                    object obj = cmd.ExecuteScalar();
                    cmd.Parameters.Clear();
                    if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    {
                        return null;
                    }
                    else
                    {
                        return obj;
                    }
                }
                catch (MySqlException ex)
                {
                    logHelper.Error(ex.Message);
                }
                cmd.Dispose();
                return null;
            }
        }

        #endregion

        /// <summary>
        /// 执行存储过程,返回数据集
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>DataSet</returns>
        public DataSet RunProcedureForDataSet(string storedProcName, IDataParameter[] parameters)
        {
            DataSet dataSet = new DataSet();
            if (!Open()) return dataSet;
            MySqlDataAdapter sqlDA = new MySqlDataAdapter();
            sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
            sqlDA.Fill(dataSet);
            return dataSet;
        }

        /// <summary>
        /// 构建 SqlCommand 对象(用来返回一个结果集，而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand</returns>
        private MySqlCommand BuildQueryCommand(MySqlConnection connection, string storedProcName,
            IDataParameter[] parameters)
        {
            MySqlCommand command = new MySqlCommand(storedProcName, connection);
            command.CommandType = CommandType.StoredProcedure;
            foreach (MySqlParameter parameter in parameters)
            {
                command.Parameters.Add(parameter);
            }
            return command;
        }

        #region 装载MySqlCommand对象

        /// <summary>
        /// 装载MySqlCommand对象
        /// </summary>
        private void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, string cmdText, MySqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
            {
                cmd.Transaction = trans;
            }
            cmd.CommandType = CommandType.Text; //cmdType;
            if (cmdParms != null)
            {
                foreach (MySqlParameter parm in cmdParms)
                {
                    cmd.Parameters.Add(parm);
                }
            }
        }
        #endregion
    }
}
